package com.hj.saapp.common.utils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.internal.Util;
import okio.Buffer;
import okio.BufferedSink;



/**
 * Created by "丁永泽" on 2016/10/8.
 */

public class HJFormBody extends RequestBody {

    private  List<String> encodedNames;
    private  List<String> encodedValues;

    private HJFormBody(List<String> encodedNames, List<String> encodedValues) {
        this.encodedNames = Util.immutableList(encodedNames);
        this.encodedValues = Util.immutableList(encodedValues);
    }

    @Override
    public MediaType contentType() {
        return MediaType.parse("application/json; charset=GBK");
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {

        writeOrCountBytes(sink, false);

    }
    private long writeOrCountBytes(BufferedSink sink, boolean countBytes) {
        long byteCount = 0L;

        Buffer buffer;
        if (countBytes) {
            buffer = new Buffer();
        } else {
            buffer = sink.buffer();
        }

        for (int i = 0, size = encodedNames.size(); i < size; i++) {
            if (i > 0) buffer.writeByte('&');
            buffer.writeString(encodedNames.get(i), Charset.forName("GBK"));
            buffer.writeByte('=');
            buffer.writeString(encodedValues.get(i),Charset.forName("GBK"));
        }

        if (countBytes) {
            byteCount = buffer.size();
            buffer.clear();
        }

        return byteCount;
    }

    public static final class Builder {
        private final List<String> names = new ArrayList<>();
        private final List<String> values = new ArrayList<>();

        public HJFormBody.Builder add(String name, String value) {
            names.add(name);
            values.add(value);
            return this;
        }

        public HJFormBody.Builder addEncoded(String name, String value) {
            names.add(name);
            values.add(value);
            return this;
        }

        public HJFormBody build() {
            return new HJFormBody(names, values);
        }
    }

}
